package com.ycy.smartcourseselection.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ycy.smartcourseselection.exception.CustomException;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

//自定义拦截器需要继承HandlerInterceptor
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {

        //如果请求不是映射到方法的话，就直接通过
        if (!(handler instanceof HandlerMethod)) return true;

        //从http请求头中获取token
        String token = request.getHeader("token");
        System.out.println("token：" + token);

        //执行验证,如果没有token 就抛出自定义异常
        if (StringUtils.isBlank(token)) throw new CustomException(ResCodeEnum.NO_PERMISSION,"缺失请求权限值");  //缺失token

        //可进行查询
        Date expireTime = JWT.decode(token).getExpiresAt();
        System.out.println("过期时间：" + expireTime);
        if(expireTime == null) throw new CustomException(ResCodeEnum.NO_PERMISSION,"验证请求权限值过期时间失败");
        boolean isExpired = expireTime.before(new Date());
        System.out.println("isExpired：" + isExpired);
        if (isExpired) throw new CustomException(ResCodeEnum.NO_PERMISSION,"请求权限值已过期");

        //token密钥加签名验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(Constant.MY_TOKEN_KEY)).build();
        try {
            jwtVerifier.verify(token);
        }catch (JWTVerificationException j) {
            throw new CustomException(ResCodeEnum.NO_PERMISSION,"请求权限值中密钥验证失败");
        }

        return true;
    }
}
